package com.xuyu.nacos.callback.listener.helper;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.xuyu.nacos.callback.listener.model.NacosConfigListenerProperties;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xuyu
 */
public class RegisterHelper {

    public static List<NacosConfigListenerProperties> getAllNeedListenConfigFile(NacosConfigManager nacosConfigManager, String appName) {
        List<NacosConfigListenerProperties> dataIds = new ArrayList<>();
        String fileExtension = nacosConfigManager.getNacosConfigProperties().getFileExtension();
        List<NacosConfigProperties.Config> sharedConfigs = nacosConfigManager.getNacosConfigProperties().getSharedConfigs();
        //这边添加的是公共配置里面的参数
        for (NacosConfigProperties.Config config : sharedConfigs) {
            NacosConfigListenerProperties nacosConfigListenerProperties = new NacosConfigListenerProperties()
                    .setGroup(config.getGroup())
                    .setSimpleDataId(config.getDataId());
            dataIds.add(nacosConfigListenerProperties);
        }
        //这边是本身读取的
        List<String> activeAndDefault = new ArrayList<>();
        String[] activeProfiles = nacosConfigManager.getNacosConfigProperties().getEnvironment().getActiveProfiles();
        String[] defaultProfiles = nacosConfigManager.getNacosConfigProperties().getEnvironment().getDefaultProfiles();
        String group = nacosConfigManager.getNacosConfigProperties().getGroup();
        activeAndDefault.addAll(Arrays.asList(activeProfiles));
        activeAndDefault.addAll(Arrays.asList(defaultProfiles));
        for (String profiles : activeAndDefault) {
            String dataId = appName + "-" + profiles + "." + fileExtension;
            NacosConfigListenerProperties nacosConfigListenerProperties = new NacosConfigListenerProperties()
                    .setSimpleDataId(dataId)
                    .setGroup(group);
            dataIds.add(nacosConfigListenerProperties);
        }
        return dataIds.stream().distinct().collect(Collectors.toList());
    }
}
